package capricornus.scene.controller
{
	import capricornus.events.StageEvent;
	import capricornus.core.StageManager;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;

	[Event(name="complete", type="flash.events.Event")]
	public class ActionSceneBackController extends EventDispatcher
	{
		internal static const ROW_COUNT:int = 16;    //行数， y
		internal static const COLUMN_COUNT:int = 25; //列数，x
		internal static const COUNT:int = ROW_COUNT * COLUMN_COUNT;
		
		private var _parent:DisplayObjectContainer;
		private var _vecCellController:Vector.<SceneCellImageController>;
		
		private var _currentCount:int = 0;
		private var _hasSendEvent:Boolean = false;
		private var _maxCellImageLoadedCount:int = 10;
		
		public function ActionSceneBackController( parent:DisplayObjectContainer )
		{
			_parent = parent;
			init();
		}
		
		private function init():void
		{
			_vecCellController = new Vector.<SceneCellImageController>();
			for( var i:int=0; i<COUNT; i++ )
			{
				var cc:SceneCellImageController = new SceneCellImageController( _parent ); 
				_vecCellController.push( cc );
				cc.addEventListener( Event.COMPLETE, onCellImageLoaded, false, 0, true );
			}
			
			onResize(null);
			StageManager.instance.addEventListener( StageEvent.RESIZE, onResize, false, 0, true );
		}
		
		private function onResize( e:StageEvent ):void
		{
			_maxCellImageLoadedCount = Math.ceil(StageManager.stageWidth/SceneCellImageController.CELL_WIDTH) *
									   Math.ceil(StageManager.stageHeight/SceneCellImageController.CELL_HEIGHT);
		}
		
		public function reset( id:String ):void
		{
			var n:int = 0;
			_currentCount = 0;
			_hasSendEvent = false;
			for( var i:int=0; i<COLUMN_COUNT; i++ )
			{
				for( var j:int=0; j<ROW_COUNT; j++ )
				{
					_vecCellController[n++].reset( id, i, j );
				}
			}
			for( ; n<COUNT; n++ )
			{
				_vecCellController[n].clear();
			}
		}
		
		public function destroy():void
		{
		}
		
		public function sceneScrollRectChange( rect:Rectangle ):void
		{
			for( var i:int=0; i<COUNT; i++ )
			{
				_vecCellController[i].viewPortChange( rect );
			}
		}
		
		private function onCellImageLoaded( e:Event ):void
		{
			_currentCount++;
			if( !_hasSendEvent && _currentCount >= _maxCellImageLoadedCount )
			{
				_hasSendEvent = true;
				
				dispatchEvent( new Event( Event.COMPLETE ) );
			}
		}
	}
}












